package cn.parllay.dingdangproject.client;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.google.gson.Gson;

import cn.parllay.dingdangproject.DingDangApplication;
import cn.parllay.dingdangproject.bean.notice.Notice;
import cn.parllay.dingdangproject.entity.BaseMsg;
import cn.parllay.dingdangproject.entity.Constants;
import cn.parllay.dingdangproject.entity.LoginMsg;
import cn.parllay.dingdangproject.entity.LoginReplyMsg;
import cn.parllay.dingdangproject.entity.MsgType;
import cn.parllay.dingdangproject.entity.PingMsg;
import cn.parllay.dingdangproject.entity.ReplyClientBody;
import cn.parllay.dingdangproject.entity.ReplyMsg;
import cn.parllay.dingdangproject.entity.ReplyServerBody;
import cn.parllay.dingdangproject.utils.SpUtils;
import cn.parllay.dingdangproject.widget.MyWindowManager1;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;

public class NettyClientHandler extends SimpleChannelInboundHandler<BaseMsg> {

    private long millis;

    //这里是断线要进行的操作
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        super.channelInactive(ctx);
        System.out.println("断线了。---------");
    }

    //这里是出现异常的话要进行的操作
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("出现异常了。。。。。。。。。。。。。");
        cause.printStackTrace();
    }

    //利用写空闲发送心跳检测消息
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;

            //向服务器发起登录
//            LoginMsg loginMsg = new LoginMsg();
//            loginMsg.setUserName("B02S0002" + millis);
//            loginMsg.setMobile("B02S0002" + millis);
            switch (e.state()) {
                //长期未向服务器发送数据 发送心跳
                case WRITER_IDLE:

                    Log.e("xintiao", "WRITER_IDLE");
                    PingMsg pingMsg = new PingMsg();
                    ctx.writeAndFlush(pingMsg);
                    //System.out.println("send ping to server--------");
                    break;
                //长期未收到服务器反馈数据
                /*case READER_IDLE:
                    ctx.writeAndFlush(loginMsg);
                    System.out.println("send loginInfo to server--------");
                    break;
                case ALL_IDLE:
                    ctx.writeAndFlush(loginMsg);
                    System.out.println("send loginInfo to server--------");
                    break;*/
                default:
                    break;
            }
        }
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, BaseMsg baseMsg) throws Exception {
        MsgType msgType = baseMsg.getType();
        switch (msgType) {
            case LOGIN: {
                //向服务器发起登录
                LoginMsg loginMsg = new LoginMsg();
                String storeNo = SpUtils.getInstance(DingDangApplication.getContext()).getString(SpUtils.STORE_NO, "");
                loginMsg.setUserName(storeNo + millis);
                loginMsg.setPassword(storeNo + millis);
                channelHandlerContext.writeAndFlush(loginMsg);
            }
            break;
            case PING: {
                System.out.println("receive ping from server----------");
            }
            break;
            case ASK: {
                ReplyClientBody replyClientBody = new ReplyClientBody("client info **** !!!");
                ReplyMsg replyMsg = new ReplyMsg();
                replyMsg.setBody(replyClientBody);
                channelHandlerContext.writeAndFlush(replyMsg);
            }
            break;
            case REPLY: {
                //收到服务端的回复(通知)
                ReplyMsg replyMsg = (ReplyMsg) baseMsg;
                ReplyServerBody replyServerBody = (ReplyServerBody) replyMsg.getBody();
                final String json = replyServerBody.getServerInfo();
                Log.e("TAG", "服务端消息: " + replyServerBody.getServerInfo());
                System.out.println("receive server msg: " + replyServerBody.getServerInfo());
                //channelHandlerContext.writeAndFlush(replyMsg);
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        popNoticeWindow(json);
                    }
                });

            }
            break;
            case LOGIN_REPLY: {
                LoginReplyMsg loginReplyMsg = (LoginReplyMsg) baseMsg;
                Constants.setClientId(loginReplyMsg.getLoginToken());
            }
            break;

            default:
                break;
        }
        ReferenceCountUtil.release(msgType);
    }

    private Handler handler = new Handler(Looper.getMainLooper());

    //弹出vip通知弹窗
    private void popNoticeWindow(String json) {
        Notice notice = new Gson().fromJson(json, Notice.class);
        MyWindowManager1.getInstance().popNoticeWindow(notice);
    }
}
